<template>
  <view class="preview">
    <swiper circular :current="currectIndex" @change="swiperChange">
      <swiper-item v-for="(item,index) in classify" :key="`${item.classid}_${index}`">
        <image v-if="previewImage.includes(index)" @click="maskChange" :src="item.picUrl" mode="aspectFill">
        </image>
      </swiper-item>
    </swiper>
    <!-- 遮罩层 -->
    <view class="mask" v-show="maskState">
      <view class="goBack" :style="{top:statusBarHeights()+'px'}" @click="goBack">
        <uni-icons type="back" size="20" color="#fff"></uni-icons>
      </view>
      <view class="count">{{currectIndex + 1}} / {{classify.length}}</view>
      <view class="time">
        <uni-dateformat :date="new Date()" format="hh:mm"></uni-dateformat>
      </view>
      <view class="date">
        <uni-dateformat :date="new Date()" format="MM月/dd日"></uni-dateformat>
      </view>
      <view class="footer">
        <view class="box" @click="clickInfo">
          <uni-icons type="info" size="28"></uni-icons>
          <view class="text">信息</view>
        </view>
        <view class="box" @click="clickScore">
          <uni-icons type="star" size="28"></uni-icons>
          <view class="text">{{currectClass.score}}分</view>
        </view>
        <view class="box" @click="clickDownLoad">
          <uni-icons type="download" size="23"></uni-icons>
          <view class="text">下载</view>
        </view>
      </view>
    </view>

    <!-- 信息-底部弹窗 -->
    <uni-popup ref="infoPopup" type="bottom">
      <view class="infoPopup">
        <view class="popHeader">
          <view></view>
          <view class="title">
            壁纸信息
          </view>
          <view class="close" @click="clickInfoClose">
            <uni-icons type="closeempty" size="18" color="#999"></uni-icons>
          </view>
        </view>
        <scroll-view scroll-y>
          <view class="content">
            <view class="row">
              <view class="lable">
                壁纸ID：
              </view>
              <text class="value">
                {{currectClass._id}}
              </text>
            </view>
            <!-- 	<view class="row">
							<view class="lable">
								分类：
							</view>
							<text class="value class">
								明星美女
							</text>
						</view> -->
            <view class="row">
              <view class="lable">
                发布者：
              </view>
              <text class="value">
                {{currectClass.nickname}}
              </text>
            </view>
            <view class="row">
              <view class="lable">
                评分：
              </view>
              <view class="value roteBox">
                <uni-rate readonly touchable="false" :value="currectClass.score" size="16" />
                <text class="score">{{currectClass.score}}分</text>
              </view>
            </view>
            <view class="row">
              <view class="lable">
                摘要：
              </view>
              <text class="value">
                {{currectClass.description}}
              </text>
            </view>
            <view class="row">
              <view class="lable">
                标签：
              </view>
              <view class="value tabs">
                <view class="tab" v-for="(item,index) in currectClass.tabs" :key="index">
                  {{item}}
                </view>
              </view>
            </view>
            <view class="copyright">
              声明：本图片来自用户投稿，非商业使用，用于免费学习交流，
              如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱513894357qq.com，
              管理将删除侵权壁纸，维护您的权益。
            </view>

            <view class="safe-area-inset-bottom"></view>
          </view>
        </scroll-view>
      </view>
    </uni-popup>

    <!-- 评分弹窗 -->
    <uni-popup ref="scorePopup" :mask-click="false">
      <view class="scorePopup">
        <view class="popHeader">
          <view></view>
          <view class="title">
            {{isScore===true?'已评过~':'壁纸评分'}}
          </view>
          <view class="close" @click="clickScoreoClose">
            <uni-icons type="closeempty" size="18" color="#999"></uni-icons>
          </view>
        </view>

        <view class="content">
          <uni-rate v-model="userScore" allowHalf :disabled="isScore" disabled-color="#FFCA3E" />
          <text class="text">{{userScore}}分</text>
        </view>

        <view class="footer">
          <button type="default" :disabled="!userScore || isScore" size="mini" plain @click="submitScore">确认评分</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
  import {
    ref
  } from 'vue';
  import {
    statusBarHeights
  } from '@/utils/system.js'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    apiGetWallScore,
    apiWriteDownLoad
  } from '@/api/api.js'

  //所有图片信息
  const classify = ref([])
  //图片预览
  const previewImage = ref([])
  const maskState = ref(true)
  const infoPopup = ref(null)
  const scorePopup = ref(null)
  //评分
  const userScore = ref(0)
  //当前图片id
  const currectId = ref(null)
  //当前图片索引
  const currectIndex = ref(null)
  //当前图片详细信息
  const currectClass = ref({})
  //判断是否评分
  const isScore = ref(false)

  //读取本地缓存
  const storgClassList = uni.getStorageSync("storgClassList") || []
  classify.value = storgClassList.map(item => {
    return {
      ...item,
      // 字符串替换
      picUrl: item.smallPicurl.replace("_small.webp", ".jpg")
    }
  })

  //遮罩层
  const maskChange = () => {
    maskState.value = !maskState.value
  }

  //信息-底部弹窗
  const clickInfo = () => {
    infoPopup.value.open()
  }

  //关闭信息-底部弹窗
  const clickInfoClose = () => {
    infoPopup.value.close()
  }

  //评分弹窗
  const clickScore = () => {
    if (currectClass.value.userScore) {
      isScore.value = true
      userScore.value = currectClass.value.userScore
    }
    scorePopup.value.open()
  }

  //关闭评分弹窗
  const clickScoreoClose = () => {
    scorePopup.value.close()
    isScore.value = false
    userScore.value = 0
  }

  //确认评分
  const submitScore = async () => {
    uni.showLoading({
      title: '加载中...'
    })
    //获取当前图片信息
    let {
      classid,
      _id: wallId
    } = currectClass.value
    let res = await apiGetWallScore({
      classid,
      wallId,
      userScore: userScore.value
    })
    uni.hideLoading()
    if (res.errCode === 0) {
      uni.showToast({
        title: '评分成功',
        icon: 'none'
      })
      classify.value[currectIndex.value].userScore = userScore.value
      uni.setStorageSync("storgClassList", classify.value)
      clickScoreoClose()
    }
  }

  //返回上一页
  const goBack = () => {
    uni.navigateBack()
  }

  //获取图像信息
  onLoad((option) => {
    currectId.value = option.id
    currectIndex.value = classify.value.findIndex(item => {
      return item._id === currectId.value
    })
    previewImgs()
    currectClass.value = classify.value[currectIndex.value]
  })

  //图片滑动
  const swiperChange = (e) => {
    currectIndex.value = e.detail.current
    previewImgs()
    currectClass.value = classify.value[currectIndex.value]
  }

  //图片预览
  const previewImgs = () => {
    previewImage.value.push(
      currectIndex.value <= 0 ? classify.value.length - 1 : currectIndex.value - 1,
      currectIndex.value,
      currectIndex.value >= classify.value.length - 1 ? 0 : currectIndex.value + 1
    )
    previewImage.value = [...new Set(previewImage.value)]
  }

  //图片下载
  const clickDownLoad = async () => {
    //条件编译
    // #ifdef H5
    uni.showModal({
      content: '请长按保存壁纸',
      showCancel: false
    })
    // #endif

    // #ifndef H5
    try {
      uni.showLoading({
        title: '下载中...',
        mask: true
      })
      //请求接口
      let {
        classid,
        _id: wallId
      } = currectClass.value
      let res = await apiWriteDownLoad({
        classid,
        wallId
      })
      if (res.errCode !== 0) throw res
      uni.getImageInfo({
        src: currectClass.value.picUrl,
        success: res => {
          uni.saveImageToPhotosAlbum({
            filePath: res.path,
            success: res => {
              uni.showToast({
                title: '保存成功,请前往相册查看',
                icon: 'none'
              })
            },
            fail: (err) => {
              if (err.errMsg === 'saveImageToPhotosAlbum:fail cancel') {
                uni.showToast({
                  title: '保存失败,请重新点击下载',
                  icon: 'none'
                })
                return
              }
              uni.showModal({
                title: "授权提示",
                content: '请开启保存到相册权限',
                showCancel: true,
                success: res => {
                  if (res.confirm) {
                    uni.openSetting({
                      success: res => {
                        console.log(res);
                        if (res
                          .authSetting[
                            'scope.writePhotosAlbum'
                          ]) {
                          uni.showToast({
                            title: '获取授权成功',
                            icon: 'none'
                          })
                        } else {
                          uni.showToast({
                            title: '获取授权失败',
                            icon: 'none'
                          })
                        }
                      }
                    })
                  }
                }
              })
            },
            complete: () => {
              uni.hideLoading()
            }
          })
        }
      })
    } catch {
      uni.hideLoading()
    }
    // #endif
  }
</script>

<style lang="scss" scoped>
  .preview {
    position: relative;
    width: 100%;
    height: 100vh;

    swiper {
      width: 100%;
      height: 100%;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .mask {
      &>view {
        position: absolute;
        left: 0;
        right: 0;
        color: #fff;
        margin: auto;
        // 根据内容算宽度
        width: fit-content;
      }

      .goBack {
        width: 60rpx;
        height: 60rpx;
        background: rgba(0, 0, 0, .5);
        left: 30rpx;
        margin-left: 0;
        border-radius: 50%;
        top: 10rpx;
        backdrop-filter: blur(10rpx);
        border: 1px solid rgba(255, 255, 255, .5);
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .time {
        font-size: 120rpx;
        top: calc(10vh + 80rpx);
        font-weight: 100;
        // 取消默认行高
        line-height: 1em;
        tsext-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
      }

      .date {
        font-size: 34rpx;
        top: calc(10vh + 240rpx);
        tsext-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
      }

      .count {
        top: 10vh;
        background: rgba(0, 0, 0, 0.3);
        font-size: 28rpx;
        border-radius: 40rpx;
        padding: 8rpx 28rpx;
        // 磨砂效果
        backdrop-filter: blur(10rpx);
      }

      .footer {
        background-color: rgba(255, 255, 255, 0.8);
        bottom: 10vh;
        width: 65vw;
        height: 120rpx;
        border-radius: 120rpx;
        color: #fff;
        display: flex;
        justify-content: space-around;
        align-items: center;
        box-shadow: 0 2rpx 0 rgba(0, 0, 0, .1);
        backdrop-filter: blur(20rpx);

        .box {
          display: flex;
          flex-direction: column;
          align-items: center;
          jcustify-content: center;
          padding: 2rpx 10rpx;

          .text {
            font-size: 26rpx;
            color: $text-font-color-2;
          }
        }
      }
    }

    .infoPopup {
      background: #fff;
      padding: 30rpx;
      border-radius: 30rpx 30rpx 0 0;
      overflow: hidden;

      .popHeader {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
          font-size: 26rpx;
          font-weight: 600;
          color: $text-font-color-2;
        }

        .close {
          padding: 6rpx;
        }
      }

      scroll-view {
        max-height: 60vh;

        .content {
          .row {
            display: flex;
            padding: 16rpx 0;
            font-size: 32rpx;
            line-height: 1.7rem;

            .lable {
              width: 140rpx;
              text-align: right;
              font-size: 30rpx;
              color: $text-font-color-3;
            }



            .value {
              flex: 1;
              width: 0;
            }

            .roteBox {
              display: flex;
              align-items: center;

              .score {
                font-size: 26rpx;
                color: $text-font-color-3;
                padding-left: 10rpx;
              }
            }

            .tabs {
              display: flex;
              flex-wrap: wrap;

              .tab {
                border: 1px solid $brand-theme-color;
                padding: 10rpx 30rpx;
                color: $brand-theme-color;
                border-radius: 40rpx;
                margin: 0 10rpx 10rpx 0;
                font-size: 22rpx;
                line-height: 1rem;
              }
            }

            .class {
              color: $brand-theme-color;
            }
          }

          .copyright {
            font-size: 28rpx;
            color: #666;
            background: #f6f6f6;
            padding: 20rpx;
            margin: 20rpx 0;
            line-height: 1.6rem;
            border-radius: 10rpx;
          }
        }
      }
    }

    .scorePopup {
      background: #fff;
      padding: 30rpx;
      width: 70vw;
      border-radius: 30rpx;
      overflow: hidden;

      .popHeader {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
          font-size: 26rpx;
          font-weight: 600;
          color: $text-font-color-2;
        }

        .close {
          padding: 6rpx;
        }
      }

      .content {
        padding: 30rpx 0;
        display: flex;
        align-items: center;
        justify-content: center;

        .text {
          color: #ffca3e;
          padding-top: 20rpx;
          text-align: right;
          line-height: 1em;
          padding-left: 10rpx;
        }
      }

      .footer {
        text-align: center;
      }
    }
  }
</style>